package eventfax.protocol

import eventfax.core._
import scala.collection.mutable.ArrayBuffer

class LineProtocol(val regex: String) {
  private val input = new ArrayBuffer[String]()
  private var last_elem = ""

  def extract(data: String) = {
    var entities = data.split(regex,-1)
    if(entities.length <= 1) {
      this.last_elem += entities(0)
    } 
    else if(entities.length == 2) {
      this.last_elem += entities(0)
      this.input += this.last_elem
      // yield members in input
      this.last_elem = entities(1)
    } else {
      this.last_elem += entities(0)
      this.input += this.last_elem
      this.input ++= entities.slice(1,(entities.length - 1))
      // yield input now
      this.last_elem = entities(entities.length - 1)
    }
  }

  def extract(data: FaxData): Unit = {
    var str_data: String = data.toString()
    extract(str_data)
  }

  def foreach(parser: String => Unit): Unit = {
    if(this.input.isEmpty) return ()
    this.input.foreach(str => {
      parser(str)
    })
    this.input.clear
  }

  def flush = {
    this.input.clear
    this.last_elem = ""
  }
}
